const McProtocolClient = require("node-mc_protocol");
import { stringToWords, decodeStringFromWords } from "./utils";

const _options = {
  pcNo: 0xff, // <McProtocol PC No.> default: 0xff
  networkNo: 0x00, // <McProtocol Network No.> default: 0x00
  unitIoNo: [0xff, 0x03], // <McProtocol Unit Io No.> default: [0xff, 0x03]
  unitStationNo: 0x00, // <McProtocol Unit Station No.> default: 0x00
  protocolFrame: "3E", // <McProtocol Frame> only: 3E(Frame)
  plcModel: "Q", // <PLC Model> [Q or iQ-R] default: Q
};

export class KlMcClient extends McProtocolClient {
  constructor(ipAddr: any, port: any, options: any = _options) {
    super(ipAddr, port, options);
  }

  async writeString(deviceName: string, str: string): Promise<boolean> {
    const words: number[] = stringToWords(str);
    return await this.setWords(deviceName, words);
  }

  async readString(deviceName: string, strLength: number) {
    const wordsLength = Math.ceil(strLength / 2);
    const words = await this.getWords(deviceName, wordsLength);
    return decodeStringFromWords(words);
  }
}
